package com.jshoperxms.action.mall.backstage.fileupload;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.json.annotations.JSON;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jshoperxms.action.mall.backstage.base.BaseTAction;
import com.jshoperxms.action.utils.config.GlobalParam;
import com.jshoperxms.action.utils.config.ReadSysConfig;
import com.jshoperxms.action.utils.fileupload.FileTools;
import com.jshoperxms.action.utils.fileupload.ImgCutTools;
import com.jshoperxms.action.utils.fileupload.qiniu.ImgFileBean;
import com.jshoperxms.action.utils.fileupload.qiniu.QiNiuConfig;
import com.jshoperxms.action.utils.fileupload.qiniu.QiNiuUploadFiles;
import com.jshoperxms.action.utils.json.GsonJson;
import com.jshoperxms.action.utils.statickey.StaticKey;
import com.qiniu.api.auth.AuthException;

@Namespace("/mall/files")
@ParentPackage("jshoperxms")
@InterceptorRefs({ @InterceptorRef("mallstack") })
public class FileUploadTAction extends BaseTAction implements
		ServletResponseAware, ServletRequestAware {
	private static final Logger log = LoggerFactory
			.getLogger(FileUploadTAction.class);

	private File fileupload;
	private String fileuploadFileName;
	private String allfilename;
	private String qqfile;
	private String directoryname;
	private String filestrs;
	private HttpServletResponse response;
	private HttpServletRequest request;

	private String creatorid;

	/**
	 * 上传图片后保存的路径
	 */
	private String mNewImgPath;
	/**
	 * 图片文件保存的目录
	 */
	private String targetSavePath;
	/**
	 * 云存储文件名
	 */
	private String cloudFileKey;
	private String extName;// 文件后缀

	private boolean sucflag;

	public String getCloudFileKey() {
		return cloudFileKey;
	}

	public void setCloudFileKey(String cloudFileKey) {
		this.cloudFileKey = cloudFileKey;
	}

	public String getExtName() {
		return extName;
	}

	public void setExtName(String extName) {
		this.extName = extName;
	}

	public String getTargetSavePath() {
		return targetSavePath;
	}

	public void setTargetSavePath(String targetSavePath) {
		this.targetSavePath = targetSavePath;
	}

	public String getmNewImgPath() {
		return mNewImgPath;
	}

	public void setmNewImgPath(String mNewImgPath) {
		this.mNewImgPath = mNewImgPath;
	}

	public File getFileupload() {
		return fileupload;
	}

	public void setFileupload(File fileupload) {
		this.fileupload = fileupload;
	}

	public String getFileuploadFileName() {
		return fileuploadFileName;
	}

	public void setFileuploadFileName(String fileuploadFileName) {
		this.fileuploadFileName = fileuploadFileName;
	}

	public String getAllfilename() {
		return allfilename;
	}

	public void setAllfilename(String allfilename) {
		this.allfilename = allfilename;
	}

	@JSON(serialize = false)
	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	@JSON(serialize = false)
	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public String getQqfile() {
		return qqfile;
	}

	public void setQqfile(String qqfile) {
		this.qqfile = qqfile;
	}

	public String getCreatorid() {
		return creatorid;
	}

	public void setCreatorid(String creatorid) {
		this.creatorid = creatorid;
	}

	public boolean isSucflag() {
		return sucflag;
	}

	public void setSucflag(boolean sucflag) {
		this.sucflag = sucflag;
	}

	
	public String getDirectoryname() {
		return directoryname;
	}

	public void setDirectoryname(String directoryname) {
		this.directoryname = directoryname;
	}

	public String getFilestrs() {
		return filestrs;
	}

	public void setFilestrs(String filestrs) {
		this.filestrs = filestrs;
	}

	/**
	 * 清理错误
	 */
	@Override
	public void validate() {
		this.clearErrorsAndMessages();

	}

	/**
	 * 异步图片
	 * 
	 * @throws JSONException
	 * @throws AuthException
	 * 
	 * @throws IOException
	 */
	@Action(value = "ajaxFileUploads", results = { @Result(name = "json", type = "json") })
	public String ajaxFileUploads() throws JSONException, AuthException {
		String extName = StaticKey.EMPTY;
		String newFileFullname = StaticKey.EMPTY;// 包含后缀的文件名
		String newFileName = StaticKey.EMPTY;// 没有包含后缀的文件名
		String nowTimeStr = StaticKey.EMPTY;
		String realpath = FileTools.isExistdir();
		SimpleDateFormat sDateFormat;
		Random r = new Random();
		String savePath = ServletActionContext.getServletContext().getRealPath(
				File.separator);
		savePath = savePath + realpath;
		HttpServletResponse response = ServletActionContext.getResponse();
		int rannum = (int) (r.nextDouble() * (99999 - 1000 + 1)) + 10000;
		sDateFormat = new SimpleDateFormat(StaticKey.DF_YYYYMMDDHHMMSS);
		nowTimeStr = sDateFormat.format(new Date());
		//String filename = request.getParameter("file");
		//Struts2 请求 包装过滤器
		MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
		//获得上传的文件名
		String filename = wrapper.getFileNames("file")[0];

		if (filename.lastIndexOf(StaticKey.DOT) >= 0) {
			extName = filename.substring(filename.lastIndexOf(StaticKey.DOT));
		}
		// 包含后缀的文件全名
		newFileFullname = nowTimeStr + rannum + extName;
		// 不包含后缀的文件全名
		newFileName = nowTimeStr + rannum;
		PrintWriter writer = null;
		InputStream is = null;
		FileOutputStream fos = null;
		try {
			writer = response.getWriter();
			is = request.getInputStream();
			fos = new FileOutputStream(new File(savePath + newFileFullname));
			IOUtils.copy(is, fos);

			ImgFileBean ifb = new ImgFileBean();
			String localFile = savePath + newFileFullname;// 已上传到本地的图片路径
			String cloudFileKey = realpath + newFileFullname;// 云上的文件名称
			String compressLocalFile = StaticKey.EMPTY;// 已上传到本地的压缩图片路径
			String compresscloudFileKey = StaticKey.EMPTY;// 云上的压缩文件名称
			Properties p = ReadSysConfig.getJConfig();
			// 检测是否启用云存储图片
			String issaveimgtocloud = p.getProperty(
					GlobalParam.ISSAVEIMGTOCLOUD, StaticKey.ZERO);
			if (StringUtils.equals(issaveimgtocloud, StaticKey.ONE)) {
				int code = QiNiuUploadFiles.upLoads(localFile, cloudFileKey);
				if (200 == code) {
					response.setStatus(HttpServletResponse.SC_OK);
					ifb.setSucflag(true);
					ifb.setCloudImg(true);
					ifb.setNormalfilepath(QiNiuConfig.QINIUIMGHOST
							+ cloudFileKey);
				}
			} else if (StringUtils.equals(issaveimgtocloud, StaticKey.ZERO)) {
				// 如果不启用云存储表示本地存储
				ifb.setSucflag(true);
				ifb.setNormalfilepath(cloudFileKey);
			}
			boolean isImg = ImgCutTools.checkIsImg(extName);
			if (isImg) {
				// 检测是否需要压缩图片
				String isimagecompression = p.getProperty(
						GlobalParam.ISIMAGECOMPRESSION, StaticKey.ZERO);
				if (isimagecompression.equals(StaticKey.ONE)) {
					// 只有当开启压缩时才执行压缩方法并保存缩略图
					int width = Integer.parseInt(p.getProperty(
							GlobalParam.THUMBNAILWIDTH,
							GlobalParam.DEFAULTWIDTH));
					int height = Integer.parseInt(p.getProperty(
							GlobalParam.THUMBNAILHEIGHT,
							GlobalParam.DEFAULTHEIGHT));
					compressLocalFile = ImgCutTools.compressImages(localFile,
							savePath, width, height);
					compresscloudFileKey = newFileName + "_"
							+ String.valueOf(width) + "_"
							+ String.valueOf(height) + extName;
					if (compressLocalFile != null) {
						if (StringUtils.equals(issaveimgtocloud, StaticKey.ONE)) {
							// 调用七牛云存储，存储压缩后的图片
							int code = QiNiuUploadFiles.upLoads(
									compressLocalFile, compresscloudFileKey);
							if (200 == code) {
								ifb.setSucflag(true);
								ifb.setCloudImg(true);
								ifb.setCompressfilepath(QiNiuConfig.QINIUIMGHOST
										+ compresscloudFileKey);
							}
						} else if (StringUtils.equals(issaveimgtocloud,
								StaticKey.ZERO)) {
							ifb.setSucflag(true);
							ifb.setCompressfilepath(realpath
									+ compresscloudFileKey);
						}
					}
				}
				// 检测是否本地保存原图，如果不保存原图意味着删除本地图片
				String issaveoriginalbitmap = p.getProperty(
						GlobalParam.ISSAVEORIGINALBITMAP, StaticKey.ZERO);
				if (StringUtils.equals(issaveoriginalbitmap, StaticKey.ZERO)) {
					// 删除本地原图
					File file = new File(localFile);
					if (file != null) {
						if (file.exists() && file.isFile() && !file.isHidden()) {
							file.delete();
						}
					}
					// 删除本地压缩图
					File compressFile = new File(compressLocalFile);
					if (compressFile != null) {
						if (compressFile.exists() && compressFile.isFile()
								&& !compressFile.isHidden()) {
							compressFile.delete();
						}
					}
				}
			}
			writer.print(GsonJson.parseDataToJson(ifb));
		} catch (FileNotFoundException ex) {
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			writer.print("{success: false}");
			log.debug(FileUploadTAction.class.getName()
					+ "has thrown an exception: " + ex.getMessage());
		} catch (IOException ex) {
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			writer.print("{success: false}");
			log.debug(FileUploadTAction.class.getName()
					+ "has thrown an exception: " + ex.getMessage());
		} finally {
			try {
				
				if (fos != null) {
					fos.close();
				}
				if (is != null) {
					is.close();
				}
				if (writer != null) {
					writer.flush();
					writer.close();
				}
			} catch (IOException e) {
				log.debug(FileUploadTAction.class.getName()
						+ "has thrown an exception:" + e.getMessage());
			}
		}
		return JSON;
	}

}
